﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.Core.Extensions;
using Microhard.WeixinMP.Models;
using Microhard.WeixinMP.Impls;
using System.Configuration;
using Microhard.WeixinMP.Const;

namespace Microhard.WeixinMP.Interfaces
{
    public class ResponseFactory
    {
        public static IWeixinRobotResponse GetResponseByType(string msgType, List<IWeixinRobotResponse> workers)
        {
            IWeixinRobotResponse inf = workers.SingleOrDefault(p => p.Command.Command.ToLowerAndTrim() == msgType.ToLowerAndTrim());
            return inf == null ? new WelcomeCommandImpl() : inf;

        }

        public static IWeixinRobotResponse GetResponseByEventKey(RequestServiceModel request, List<IWeixinRobotResponse> workers)
        {
            if (request.Event.Content.Event == WeixinMsgType.Subscribe)
                return null;
            if (request.Event.Content.Event == WeixinMsgType.Unsubscribe)
                return null;
            //使用key辨别
            IWeixinRobotResponse inf = workers.SingleOrDefault(p => p.Command.Event == request.Event.Content.Event
                && p.Command.EventKey == request.Event.Content.EventKey);
            //使用方法辨别
            if (inf == null)
            {
                foreach (var i in workers)
                {
                    if (i.IsCallMe(request) && i.Command.Event == request.Event.Content.Event)
                    {
                        inf = i;
                        break;
                    }
                };
            }
            if (inf == null)
            {
                inf = workers.SingleOrDefault(c => c.Command.Command == WeixinConst.WELCOMETAG);
            }
            return inf == null ? new WelcomeCommandImpl() : inf;
        }

        public static IWeixinRobotResponse GetResponseByTxtRequest(RequestServiceModel txtRequest, List<IWeixinRobotResponse> workers)
        {
            //使用key辨别
            IWeixinRobotResponse inf = workers.SingleOrDefault(p => p.Command.Command.ToLowerAndTrim() == txtRequest.Txt.Content.Content.ToLowerAndTrim());
            //使用方法辨别
            if (inf == null)
            {
                workers.ForEach(i =>
                {
                    try
                    {
                        if (i.IsCallMe(txtRequest))
                        {
                            inf = i;
                        }
                    }
                    catch (Exception ex)
                    { 
                        
                    }
                });
            }
            if (inf == null)
            {
                inf = workers.SingleOrDefault(c => c.Command.Command == WeixinConst.WELCOMETAG);
            }
            return inf == null ? new WelcomeCommandImpl() : inf;
        }

    }
}
